<template>
  <div>
    <div class="details_box" v-loading="loading">
      <div style="width: 100%; height: 40px;">
        <el-button type="warning" size="small" link style="float: right; margin-top: 10px; margin-left: 10px;"
          @click="reback()">返回</el-button>
      </div>
      <div class="sapmle_box">
        <el-descriptions title="" :column="1">
          <el-descriptions-item label="用户名">{{ checkedSeqSample.userName ? checkedSeqSample.userName : checkedSeqSample.fmtUserName }}</el-descriptions-item>
          <el-descriptions-item label="样本编号">{{ checkedSeqSample.number }}</el-descriptions-item>
        </el-descriptions>
        <el-card shadow="never">
          <div style="width: 100%;">
            <el-button type="success" @click="openDialog()"><i class="el-icon-circle-plus"></i> 新增</el-button>
          </div>
          <el-table v-loading="loading" :data="dataList" highlight-current-row border :cell-style="cellStyle" style="margin-top: 10px;">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" width="55" type="index" />
            <el-table-column label="报告名称" prop="pdfName" />
            <el-table-column label="报告类型" prop="reportType">
              <template slot-scope="scope">
                {{ scope.row.reportType == 'INTERPRET_REPORT' ? '解读报告' : '样本报告' }}
              </template>
            </el-table-column>
            <el-table-column label="所属应用" prop="dfApplicationName" />
            <el-table-column label="关联模板" prop="reportTemplateName" />
            <el-table-column label="本地模板" prop="templateFile" width="165">
              <template slot-scope="scope">
                <template v-if="scope.row.reportTemplateId && (scope.row.templateFile == null || !scope.row.templateFile)">
                  <el-link type="danger">不存在</el-link><el-tag style="margin-left: 8px; cursor: pointer;" @click="copyApplicationTemplate(scope.row)">复制应用模板</el-tag>
                </template>
                <template v-if="scope.row.reportTemplateId && (scope.row.templateFile != null && scope.row.templateFile)">
                  <el-link type="success" @click="sampleTemplateFilePath(scope.row.id)">&nbsp;存&nbsp;在&nbsp;</el-link><el-tag type="danger" style="margin-left: 8px; cursor: pointer;" @click="delSampleTemplateFile(scope.row)">删除本地模板</el-tag>
                </template>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" min-width="120" width="320">
              <template #default="scope">
                <el-button type="primary" size="small" :disabled="!scope.row.reportFile" link @click="viewReportPdf(scope.row)">预 览</el-button>
                <el-button type="warning" size="small" link @click="openDialog(scope.row)">编 辑</el-button>
                <!-- <el-button type="primary" size="small" link @click="copyFileUrl(scope.row.id)"
                  icon="el-icon-view">复制地址</el-button> -->
                <el-button type="success" size="small" v-if="!scope.row.reportFile" link @click="viewFile(scope.row)">生成报告</el-button>
                <el-button type="info" size="small" v-if="scope.row.reportFile" link @click="viewFile(scope.row)">重新生成</el-button>
                <el-button type="danger" size="small" :disabled="checkedSeqSample.sampleStatus == 'COMPLETED' && scope.row.reportType == 'SEQ_SAMPLE_REPORT'" link @click="del(scope.row)">删 除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="float: right;">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </el-card>
      </div>
    </div>

    <el-dialog width="500px" :visible.sync="checkSampleDataVisible" title="样本数据校验" :close-on-click-modal="false">
      <p v-if="diffDataList.length != 0" style="color: red; text-align: center;">数据校验完成，共存在 {{ diffDataList.length }}
	        项KEY缺失，请检查服务器样本文件是否正确！</p>
      <p v-if="diffDataList.length == 0" style="color: green; text-align: center;">数据校验完成，不存在KEY缺失情况</p>
      <el-button type="success" style="margin-top: 10px; margin-bottom: 10px;" @click="genePdfReport">继续生成报告</el-button>
      <el-switch style="margin-left: 10px;" v-model="geneCoverContent" active-text="封面加姓名" inactive-text="封面"></el-switch>
      <el-table v-loading="loading" :data="diffDataList" highlight-current-row border height="500px">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" type="index" />
        <el-table-column label="KEY" prop="key" />
        <el-table-column label="#"><span style="color: red;">缺失</span></el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog width="800px" :visible.sync="showGenePdfUrlVisible" title="预览样本报告" :close-on-click-modal="false">
      <el-button type="success" size="small" link style="float: right; margin-top: 10px; margin-left: 10px;"
          @click="downlaodPdf()">下载报告</el-button>
      <iframe id="iframeDiv" width="100%" height="600px" frameborder="no" allowtransparency="true"
        :src="htmlPdUrl" style="margin-top: 5px;"></iframe>
      <el-button type="primary" style="margin-top: 5px; margin-bottom: 5px; float: right;"
        @click="geneReportEnd">完成</el-button>
    </el-dialog>

    <el-dialog :visible.sync="sampleReportDialog.visible" :title="sampleReportDialog.title" width="400px" :close-on-click-modal="false"
      :before-close="closeSampleReportDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="报告名称" prop="pdfName">
          <el-input type="text" v-model="formData.pdfName"></el-input>
        </el-form-item>
        <el-form-item label="所属应用" prop="dfApplicationId">
          <el-select v-model="formData.dfApplicationId" @change="changeApplication">
            <el-option v-for="field in applicationList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属关联模板" prop="reportTemplateId">
          <el-select v-model="formData.reportTemplateId">
            <el-option v-for="field in appTemplateList" :key="field.id" :label="field.name" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报告类型" prop="reportType">
          <el-select v-model="formData.reportType">
            <el-option label="测序样本报告" value="SEQ_SAMPLE_REPORT"></el-option>
            <el-option label="解读报告" value="INTERPRET_REPORT"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联报告" prop="parentId" v-if="formData.reportType == 'INTERPRET_REPORT'">
          <el-select v-model="formData.parentId">
            <el-option v-for="field in sampleReportParentList" :disabled="field.id == formData.id" :key="field.id" :label="field.pdfName" :value="field.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeSampleReportDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import reportSampleApi from '@/api/report/reportSample';
import dfApplicationApi from '@/api/analysis/application';
import reportTemplateApi from '@/api/report/template'
import reportIndexApi from '@/api/report';

import seqSampleReportApi from '@/api/sequence/seqSampleReport';
export default {
  name: 'seqSampleReport',
  props: {
    checkedSeqSample: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      loading: false,
      dataList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      checkedSampleReport: {},
      geneCoverContent: false,
      checkSampleDataVisible: false,
      diffDataList: [],
      htmlPdUrl: '',
      showGenePdfUrlVisible: false,
      sampleReportDialog: {},
      rules: {},
      formData: {},
      applicationList: [],
      appTemplateList: [],

      sampleReportParentList: [],
    }
  },
  methods: {
    downlaodPdf () {
      seqSampleReportApi.downloadReport(this.checkedSampleReport.id).then((res) => {
        const blob = new Blob([res], {
          type: 'application/pdf'
        })
        let link = document.createElement('a')
        let body = document.querySelector('body')
        link.href = window.URL.createObjectURL(blob)
        link.style.display = 'none'
        link.download = this.checkedSeqSample.number + '.pdf'
        body.appendChild(link)
        link.click()
        body.removeChild(link)
        window.URL.revokeObjectURL(link.href)
      });
    },
    viewReportPdf (row) {
      this.checkedSampleReport = row;
      seqSampleReportApi.downloadReport(row.id).then((res) => {
        this.showGenePdfUrlVisible = true;
        const binaryData = [];
        binaryData.push(res);
        let blob = new Blob(binaryData, { type: 'application/pdf' });
        this.htmlPdUrl = window.URL.createObjectURL(blob) + '#toolbar=0&navpanes=0&scrollbar=0';
      });
    },
    delSampleTemplateFile (row) {
      this.$confirm('此操作将删除本地模板文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        seqSampleReportApi.delSampleTemplateFile(row.id).then(res => {
          this.$message({ message: '样本模板文件删除成功！', type: 'success' });
          this.init();
        })
      }).catch(() => {});
    },
    init () {
      seqSampleReportApi.page({
        number: this.currentPage,
        size: this.pageSize,
        seqSampleId: this.checkedSeqSample.id,
      }).then(res => {
        this.dataList = res.data.content;
      })
    },
    addOrUpdate () {
      this.formData.seqSampleId = this.checkedSeqSample.id;
      this.formData.sampleType = this.checkedSeqSample.type;
      if (this.checkedSampleReport) {
        seqSampleReportApi.update(this.formData).then(res => {
          this.$set(this.sampleReportDialog, 'visible', false);
          this.$message({ message: '编辑成功！', type: 'success' });
          this.init();
        })
      } else {
        seqSampleReportApi.add(this.formData).then(res => {
          this.$set(this.sampleReportDialog, 'visible', false);
          this.$message({ message: '新增成功！', type: 'success' });
          this.init();
        })
      }
    },
    changeApplication(val) {
      this.appTemplateList = [];
      reportTemplateApi.listByApplication(val).then(r => {
        this.appTemplateList = r.data;
      })
    },
    openDialog (row) {
      this.checkedSampleReport = row;
      this.$set(this.sampleReportDialog, 'visible', true);
      seqSampleReportApi.reportList(this.checkedSeqSample.id).then(r => {
        this.sampleReportParentList = r.data;
        dfApplicationApi.list().then(res => {
          this.applicationList = res.data;
          if (this.applicationList.length != 0) {
            reportTemplateApi.listByApplication(this.applicationList[0].id).then(r => {
              this.appTemplateList = r.data;
            })
            if (!row) {
              this.$set(this.sampleReportDialog, 'title', '新增样本报告');
            } else {
              this.$set(this.sampleReportDialog, 'title', '编辑样本报告');
              seqSampleReportApi.get(row.id).then(re => {
                this.formData = re.data
              })
            }
          }
        })
      })
      
    },
    closeSampleReportDialog () {
      this.$set(this.sampleReportDialog, 'visible', false);
    },
    sampleTemplateFilePath (id) {
      seqSampleReportApi.getSampleTemplateFilePath(this.checkedSeqSample.id, id).then(res => {
        if (res.data == '') {
          this.$message.error('复制失败，当前样本没有上传输出文件！');
          return;
        }
        this.$copyText(res.data);
        this.$message({ message: '已复制到剪切板！', type: 'success' });
      })
    },
    copyApplicationTemplate (row) {
      this.$confirm('此操作将基于当前应用模板生成样本模板文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        seqSampleReportApi.copyApplicationTemplate(row.id).then(res => {
          this.$message({ message: '样本模板文件生成成功！', type: 'success' });
          this.init();
        })
      }).catch(() => {});
    },
    viewFile(row) {
      this.checkedSampleReport = row;
      seqSampleReportApi.diff(row.id).then(res => {
        let data = res.data;
        this.checkSampleDataVisible = true;
        this.diffDataList = data;
      })
    },
    genePdfReport() {
      const loading = this.$loading({
        lock: true,
        text: 'PDF 解析中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      seqSampleReportApi.parseReport(this.checkedSampleReport.id).then(res1 => {
        console.log(res1)
        if (res1.error) {
          this.$message({
            showClose: true,
            message: res1.data,
            type: 'error',
            duration: 0,
            customClass: 'messageErrorClass'
          });
          loading.close();
          return;
        }
        reportIndexApi.genePdf(this.checkedSampleReport.reportTemplateId, true, this.checkedSampleReport.id, this.geneCoverContent).then((res) => {
          loading.close();
          let result = res;
          var binaryData = [];
          binaryData.push(result);
          let Blobs = new Blob(binaryData, { type: 'application/pdf' });
          this.htmlPdUrl = URL.createObjectURL(Blobs);
          this.checkSampleDataVisible = false;
          this.viewFileVisible = false;
          this.showGenePdfUrlVisible = true;
        });
      })
    },
    geneReportEnd() {
      this.showGenePdfUrlVisible = false;
    },
    cellStyle () {},
    reback() {
      this.$emit("close");
    },
    handleSizeChange(val) {
      this.pageSize = val * 1;
      this.init();
    },
    handleCurrentChange(val) {
      this.currentPage = val * 1;
      this.init();
    },
    del (row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        seqSampleReportApi.delete(row.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.init()
        })
        
      }).catch(() => {});
    },
  },
  mounted() {
    this.init();
  }
}
</script>

<style>
.messageErrorClass .el-message__content  {
  max-height: 300px;
  overflow: auto;
}
</style>
<style scoped>

.details_box {
  width: 100%;
  padding: 0 2%;
  background-color: white;
}

.sapmle_box {
  width: 100%;
  height: calc(100vh - 220px);
  margin-bottom: 10px;
}

.sapmle_box_view {
  width: 100%;
  height: calc(100vh - 160px);
  /* margin-bottom: 10px; */
}


.ifram_height {
  width: 100%;
  height: calc(100vh - 240px);
}

.ifram_height_view {
  width: 100%;
  height: calc(100vh - 210px);
}

.dialog-footer {
  padding-bottom: 10px;
  text-align: end;
}</style>
